 import { PiniaPluginContext, StateTree } from "pinia"
import { PINIA_CACHE_KEY } from "../config/common.cfg"
import { decodeApi } from "../utils"

//自己写的数据持久化插件
export default function persisteStatePlugin({ store }:PiniaPluginContext) {
    store.$subscribe(function (_: any, _state:StateTree) {
        sessionStorage.setItem(PINIA_CACHE_KEY,JSON.stringify(_state))
    })
}
/**
 * 初始化state数据
 * @returns any
 */
export function initState() {
    let cache = sessionStorage.getItem(PINIA_CACHE_KEY)

    if (!cache) {
        return {}
    } else {
        try {
            return JSON.parse(decodeApi(cache))
        } catch {
            return {}
        }
    }
}